package com.rk.app.poll.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.rk.app.poll.client.viewer.PollViewerFactory;

public class PollMain implements EntryPoint {

	DockPanel mainPanel = new DockPanel();

	VerticalPanel topPanel = new VerticalPanel();

	private String centerWidgetType = "poll_list";

	private Widget centralWidget = null;

	private VerticalPanel footerPanel = new VerticalPanel();

	private final PollServiceAsync pollingService = GWT.create(PollService.class);

	private Poll[] polls = null;

	// private FlexTable pollFlexTable = new FlexTable();

	int row = -1;

	private VerticalPanel defaultCenterPanel = new VerticalPanel();

	protected boolean signedIn;

	public void onModuleLoad() {

		pollingService.getAllPolls(new AsyncCallback<Poll[]>() {

			public void onFailure(Throwable caught) {

			}

			public void onSuccess(Poll[] result) {
				polls = result;
				// if (polls == null || polls.length <= 0) {
				// Window.alert("No poll to show, visit later");
				// } else {
				initPR();
				// }
			}

		});
	}

	private void initDefaultCenterPanel() {
		defaultCenterPanel.setWidth("100%");
		defaultCenterPanel.setStyleName("pageBackground");
		DecoratedStackPanel stackPanel = new DecoratedStackPanel();
		stackPanel.setWidth("100%");
		if (polls != null && polls.length > 0) {
			for (int i = 0; i < polls.length; i++) {
				Poll p = polls[i];
				String header = getPollHeader(p);
				Widget details = getPollDetails(p);
				stackPanel.add(details, header, true);
			}
		} else {
			stackPanel.add(new HTML("Create new poll using menu <font style=\"color:green\"><b>Poll > Create New</b></font>"), "No poll yet created.", true);
		}
		defaultCenterPanel.add(stackPanel);
		centerWidgetType = "poll_list";
		centralWidget = defaultCenterPanel;
	}

	private void initPR() {
		initTopPanel();
		initDefaultCenterPanel();
		mainPanel.setWidth("100%");
		topPanel.setWidth("100%");

		footerPanel.setSpacing(5);
		footerPanel.setWidth("100%");
		footerPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		footerPanel.add(new HTML("<p>@2009 copyright<p>"));

		mainPanel.add(topPanel, DockPanel.NORTH);
		mainPanel.add(centralWidget, DockPanel.CENTER);
		mainPanel.add(footerPanel, DockPanel.SOUTH);
		// mainPanel.add(footerPanel, DockPanel.EAST);

		mainPanel.setStyleName("pageBackground");

		RootPanel.get().add(mainPanel);
	}

	private Widget getNewPoll() {
		return new NewPollWidget();
	}

	private void initTopPanel() {

		Command newPollCommand = new Command() {
			public void execute() {
				if (signedIn) {
					if (!"new_poll".equals(centerWidgetType)) {
						centralWidget.removeFromParent();
						centerWidgetType = "new_poll";
						centralWidget = getNewPoll();
						mainPanel.add(centralWidget, DockPanel.CENTER);
					}
				} else {
					Window.alert("Please sing in to create new poll");
				}
			}
		};
		Command homeCommand = new Command() {
			public void execute() {
				if (!"poll_list".equals(centerWidgetType)) {
					centralWidget.removeFromParent();
					centerWidgetType = "poll_list";
					centralWidget = defaultCenterPanel;
					mainPanel.add(centralWidget, DockPanel.CENTER);
				}
			}
		};

		// Create a menu bar
		MenuBar menu = new MenuBar();
		menu.setAutoOpen(true);
		menu.setWidth("100%");
		menu.setAnimationEnabled(true);
		// MenuBar home = new MenuBar(false);
		MenuItem homeItem = new MenuItem("Home", homeCommand);// , home);
		menu.addItem(homeItem);
		MenuBar fileMenu = new MenuBar(true);
		fileMenu.setAnimationEnabled(true);
		menu.addItem(new MenuItem("Poll", fileMenu));
		// fileMenu.addSeparator();
		fileMenu.addItem("Create New", newPollCommand);

		HorizontalPanel menuPanel = new HorizontalPanel();
		menuPanel.setWidth("100%");
		menuPanel.add(menu);

		final HorizontalPanel bannerPanel = new HorizontalPanel();
		bannerPanel.setWidth("98%");
		bannerPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
		topPanel.add(bannerPanel);

		topPanel.add(menuPanel);
		topPanel.setSpacing(5);

		String uri = Window.Location.getPath();
		pollingService.getSignInURL(uri, new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			public void onSuccess(String result) {
				if (result != null && result.toLowerCase().indexOf("sign out") >= 0) {
					signedIn = true;
				}
				bannerPanel.add(new HTML(result));
			}
		});
	}

	private void showPoll(Poll poll) {
		if (!"show_poll".equals(centerWidgetType)) {
			centerWidgetType = "show_poll";
			centralWidget.removeFromParent();
			centralWidget = new PollViewWidget(poll);
			mainPanel.add(centralWidget, DockPanel.CENTER);
		}
	}

	private void showResult(Poll poll) {
		if (!"show_result".equals(centerWidgetType)) {
			centerWidgetType = "show_result";
			centralWidget.removeFromParent();
			centralWidget = PollViewerFactory.createPollResultViewer(poll);
			mainPanel.add(centralWidget, DockPanel.CENTER);
		}
	}

	private Widget getPollDetails(final Poll p) {
		VerticalPanel panel = new VerticalPanel();
		panel.setWidth("100%");
		// panel.setStyleName("formPanel");
		Anchor poll = new Anchor("Submit Vote");
		poll.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				showPoll(p);
			}
		});
		Anchor viewResult = new Anchor("View Results");
		viewResult.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				showResult(p);
			}
		});
		panel.setSpacing(5);
		panel.add(poll);
		panel.add(viewResult);
		return panel;
	}

	public static String getPollHeader(Poll p) {
		String color = p.isOpen() ? "green" : "red";
		String header = "<table width='100%' <tr>";
		header += "<td align='left'rowspan='2'><h4 color='" + color + "'>" + p.getPollQuestion() + "<h4></td>";
		if (p.isOpen()) {
			header += "<td valign='bottom' align='right' style='color:green;font-weight: bold'>Open Till</td>";
		} else {
			header += "<td valign='bottom' align='right' style='color:red;font-weight: bold'>Closed At</td>";
		}
		header += "<tr><td valign='top' align='right'>"
				+ DateTimeFormat.getMediumDateTimeFormat().format(p.getEndsOn()) + "</td></tr></table>";

		return header;
	}
}
